package com.sunsheng.modules.excel.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson.JSON;
import com.sunsheng.modules.excel.entity.ExcelTestEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

@Slf4j
@Controller
@RequestMapping("/excel")
public class excelController {
    //参考案例
    //https://easyexcel.opensource.alibaba.com/
    @ResponseBody
    @RequestMapping("/simpleRead")
    public void simpleRead() {
        // 写法1：JDK8+ ,不用额外写一个DemoDataListener
        // since: 3.0.0-beta1
        String fileName = "D:\\下载\\write1.xlsx";
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        // 这里每次会读取100条数据 然后返回过来 直接调用使用数据就行
        EasyExcel.read(fileName, ExcelTestEntity.class, new PageReadListener<ExcelTestEntity>(dataList -> {
            for (ExcelTestEntity demoData : dataList) {
                System.out.println(JSON.toJSONString(demoData));
            }
        })).sheet().doRead();
    }

    @ResponseBody
    @RequestMapping("/write")
    public void write() {
        List<ExcelTestEntity> list = new LinkedList<>();
        Random random = new Random();
        for (int i = 1; i <= 10; i++) {
            ExcelTestEntity entity = new ExcelTestEntity();
            entity.setId("" + i);
            entity.setName(UUID.randomUUID().toString().replaceAll("-", ""));
            entity.setPwd(UUID.randomUUID().toString().replaceAll("-", ""));
            entity.setAge(random.nextInt(100) + "");
            list.add(entity);
        }

        EasyExcel.write("D:\\下载\\write1.xlsx")
                .excelType(ExcelTypeEnum.XLSX)
                .sheet(1)
                .doWrite(list);
    }
}
